//
//  SessionUpLoadViewController.m
//  NSURLSessionStudyDemo
//
//  Created by 赵忠鹏 on 2018/5/7.
//  Copyright © 2018年 内蒙小猿. All rights reserved.
//

#import "SessionUpLoadViewController.h"

#define Kboundary  @"----WebKitFormBoundary35cxmtFcIglrlsad"
#define KNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]

@interface SessionUpLoadViewController ()<NSURLSessionDataDelegate>

@property (weak, nonatomic) IBOutlet UIProgressView *sessionDelegateprogress;

@property (nonatomic, strong) NSURLSession *session;

@end

@implementation SessionUpLoadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (NSURLSession *)session{
    if (_session == nil) {
        
        NSURLSessionConfiguration *configuration =[NSURLSessionConfiguration defaultSessionConfiguration];
        // 请求超时时间
        configuration.timeoutIntervalForRequest = 10;
        // 是否让用蜂窝网络
        configuration.allowsCellularAccess = NO;
        
        _session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}


- (IBAction)sessionUpLoadTaskButtonClick:(id)sender {
    //: 1.创建 Session
    NSURLSession *session = [NSURLSession sharedSession];
    
    //: 2.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/upload"]];
    
    //: 3.设置请求方式
    request.HTTPMethod = @"POST";
    
    //: 4.设置请求头
    NSString *header = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",Kboundary];
    [request setValue:header forHTTPHeaderField:@"Content-Type"];
    
    //: 5.开始请求  无法监听进度
    /*
     第一个参数：请求对象
     第二个参数：请求体（要上传的文件数据）
     block回调：
     NSData:响应体
     NSURLResponse：响应头
     NSError：请求的错误信息
     */
    NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:[self getBody] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"NSURLSessionUploadTask" message:[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [view show];
            });
        }
    
    }];
    // 6.开始任务
    [task resume];
    
}



- (IBAction)sessionDelgateUploadButtonClick:(id)sender {
    //1 创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/upload"]];
    //2 设置请求方法
    request.HTTPMethod = @"POST";
    
    //3.设置请求头
    NSString *header = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",Kboundary];
    [request setValue:header forHTTPHeaderField:@"Content-Type"];
    //4设置文件上传的文件内容
    [[self.session uploadTaskWithRequest:request fromData:[self getBody]] resume];
}

#pragma mark  NSURLSessionDataDelegate
/*
 bytesSent:本次上传数据大小
 totalBytesSent:总共上传了多少
 totalBytesExpectedToSend:文件大小
 */
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
    NSLog(@"%f",1.0 *totalBytesSent /totalBytesExpectedToSend);
    self.sessionDelegateprogress.progress = 1.0 *totalBytesSent /totalBytesExpectedToSend;
}



-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if (!error) {
        NSLog(@"传完了");
    }
}





-(NSData *)getBody
{
    
    //5.设置请求体
    NSMutableData *fileData = [NSMutableData data];
    
    //5.1 文件参数
    /*
     --分隔符
     Content-Disposition: form-data; name="file"; filename="123.png"
     Content-Type: image/png
     空行
     文件数据
     */
    NSString *str = [NSString stringWithFormat:@"--%@",Kboundary];
    [fileData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
    [fileData appendData:KNewLine];
    [fileData appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"123.png\"" dataUsingEncoding:NSUTF8StringEncoding]];
    [fileData appendData:KNewLine];
    [fileData appendData:[@"Content-Type: image/png" dataUsingEncoding:NSUTF8StringEncoding]];
    [fileData appendData:KNewLine];
    [fileData appendData:KNewLine];
    [fileData appendData:KNewLine];
    
    UIImage *image = [UIImage imageNamed:@"123"];
    NSData *imageData = UIImagePNGRepresentation(image);
    [fileData appendData:imageData];
    [fileData appendData:KNewLine];
    
    //5.2 非文件参数
    /*
     --分隔符
     Content-Disposition: form-data; name="username"
     空行
     yy
     */
    
    [fileData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
    [fileData appendData:KNewLine];
    [fileData appendData:[@"Content-Disposition: form-data; name=\"username\"" dataUsingEncoding:NSUTF8StringEncoding]];
    [fileData appendData:KNewLine];
    [fileData appendData:KNewLine];
    [fileData appendData:KNewLine];
    [fileData appendData:[@"yy" dataUsingEncoding:NSUTF8StringEncoding]];
    [fileData appendData:KNewLine];
    
    //5.3 结尾标识
    /*
     --分隔符--
     */
    [fileData appendData:[[NSString stringWithFormat:@"--%@--",Kboundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [fileData appendData:KNewLine];
    
    return fileData;
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
